package www.hz.domain.strategy.service.rule.chain.factory;

import lombok.*;
import org.springframework.stereotype.Service;
import www.hz.domain.strategy.model.entity.StrategyEntity;
import www.hz.domain.strategy.repository.IStrategyRepository;
import www.hz.domain.strategy.service.armory.IStrategyDispatch;
import www.hz.domain.strategy.service.rule.chain.ILogicChain;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @className: DefaultChainFactory
 * @Description: TODO
 * @version: v1.８.0
 * @author: hz
 * @date: 2025/3/16 9:35
 */
@Service
public class DefaultChainFactory {
    private final Map<String, ILogicChain> logicChainGroup;
    protected IStrategyRepository repository;
    public DefaultChainFactory(Map<String, ILogicChain> logicChainGroup, IStrategyRepository repository) {
        this.logicChainGroup = logicChainGroup;
        this.repository = repository;
    }
    /**
     * 通过策略ID，构建责任链
     *
     * @param strategyId 策略ID
     * @return LogicChain
     */
    public ILogicChain openLogicChain(Long strategyId) {
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruleModels = strategyEntity.ruleModels();
         // 如果未配置策略规则，则只装填一个默认责任链
            if (null == ruleModels || 0 == ruleModels.length) return logicChainGroup.get("default");
            //如果有rule_black改一下ruleModels数组位置，把rule_black放在最前面
        if(Arrays.asList(ruleModels).contains("rule_blacklist")){
            ruleModels= Stream.concat(
                    Arrays.stream(ruleModels).filter("rule_blacklist"::equals),
                    Arrays.stream(ruleModels).filter(s -> !"rule_blacklist".equals(s))
            ).toArray(String[]::new);
        }

        // 按照配置顺序装填用户配置的责任链；rule_blacklist、rule_weight 「注意此数据从Redis缓存中获取，如果更新库表，记得在测试阶段手动处理缓存」
        ILogicChain logicChain=logicChainGroup.get(ruleModels[0]);
        ILogicChain currentChain = logicChain;
        for (int i=1; i<ruleModels.length; i++){
            ILogicChain nextChain = logicChainGroup.get(ruleModels[i]);
            currentChain=currentChain.appendNext(nextChain);
        }
        currentChain.appendNext(logicChainGroup.get("default"));
        return logicChain;
    }
    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {
        /**
         * 抽奖奖品ID - 内部流转使用
         */
        private Integer awardId;
        /**
         * 抽奖类型；黑名单抽奖、权重规则、默认抽奖
         */
        private String logicModel;
        /**
         * 抽奖奖品规则
         */
        private String awardRuleValue;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WEIGHT("rule_weight", "权重规则"),
        ;

        private final String code;
        private final String info;

    }



}